import os.path

from openpyxl import load_workbook
from openpyxl.workbook import Workbook
from openpyxl.worksheet.worksheet import Worksheet

basename = os.path.dirname(__file__)
filename = os.path.join(basename, 'data.xlsx')

# 打开已存在的工作簿
wb: Workbook = load_workbook(filename)

# 打开活动工作表
ws: Worksheet = wb.active

# 获取最大行/最大列
max_row = ws.max_row
max_col = ws.max_column
print(f'max_row: {max_row}, max_col: {max_col}')

# 获取单元格的值
print(ws['A1'].value)
print(ws.cell(1, 1).value)

# 获取某行/某列的值
print([cell.value for cell in ws[1]])
for cell in ws.iter_rows(min_row=1, max_row=1, values_only=True):
    print(cell)
for col in range(1, max_col+1):
    print(ws.cell(1, col).value)

print([cell.value for cell in ws['A']])
for cell in ws.iter_cols(min_col=1, max_col=1, values_only=True):
    print(cell)
for row in range(1, max_row+1):
    print(ws.cell(row, 1).value)

# 获取矩形区域
for row in ws.iter_rows(min_row=2, min_col=2, max_col=5, values_only=True):
    print(', '.join(row))

# 关闭工作簿
wb.close()
